package com.wbao.dianniu.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.OptionsPickerView.OnOptionsSelectListener;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.PickerView;
import com.wbao.dianniu.customView.PickerView.onSelectListener;
import com.wbao.dianniu.data.ChildZone;
import com.wbao.dianniu.data.RecruitAddData;
import com.wbao.dianniu.data.RecruitListData;
import com.wbao.dianniu.data.Zone;
import com.wbao.dianniu.listener.IRecruitAddListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.RecruitAddManager;
import com.wbao.dianniu.manager.RecruitListChangeManager;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 岗位编辑/新增
 * 
 * @author yejianjun
 *
 */
public class RecruitReleaseActivity extends BaseActivity implements IRecruitAddListener {
	/** 省列表 */
	private LinkedList<ChildZone> province_list = new LinkedList<ChildZone>();
	/** 市列表 */
	private ArrayList<LinkedList<ChildZone>> city_list = new ArrayList<>();
	/** 省数据 */
	private ArrayList<String> provinceList = new ArrayList<>();
	/** 市数据 */
	private ArrayList<ArrayList<String>> cityList = new ArrayList<>();
	private OptionsPickerView pvOptions;
	//弹出选择对话框
	private Dialog dialog;
	private RecruitAddManager manager;
	private RelativeLayout rl_salary;
	private RelativeLayout rl_tryout;
	private RelativeLayout rl_address;
	private RelativeLayout rl_experience;
	private RelativeLayout rl_education;
	private EditText et_post;
	private TextView tv_salary;
	private TextView tv_tryout;
	private TextView tv_address;
	private EditText et_recruitCount;
	private TextView tv_experience;
	private TextView tv_education;
	private EditText et_describe;
	private Button releaseBtn;
	private String strMoney="";
	private String strXueli="";
	private Dialog pDialog;
	private String[] tryoutList = new String[]{"需要试用","不需试用"};
	private String strTryout="";
	private String strExperience="";
	Integer recruitId = null;
	private boolean isClick = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_recruit_release,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
		setTitleName(getResources().getString(R.string.edit_recurit));
		ImageButton backButton = getBackView();
		backButton.setImageResource(R.drawable.cancel_res_icon);
		Button fbBtn = getRightTextButton();
		fbBtn.setText(getResources().getString(R.string.preview));
		fbBtn.setOnClickListener(this);
		init();
		initData();
		manager = new RecruitAddManager(this);
		manager.addRecruitAddListener(this);
	}
	private void init(){
		rl_salary = (RelativeLayout) findViewById(R.id.recruit_release_salary_rl);
		rl_tryout = (RelativeLayout) findViewById(R.id.recruit_release_tryout_rl);
		rl_address = (RelativeLayout) findViewById(R.id.recruit_release_address_rl);
		rl_experience = (RelativeLayout) findViewById(R.id.recruit_release_experience_rl);
		rl_education = (RelativeLayout) findViewById(R.id.recruit_release_education_rl);
		et_post =  (EditText) findViewById(R.id.recruit_release_post);
		tv_salary = (TextView) findViewById(R.id.recruit_release_salary);
		tv_tryout = (TextView) findViewById(R.id.jrecruit_release_tryout);
		tv_address = (TextView) findViewById(R.id.recruit_release_address);
		et_recruitCount = (EditText) findViewById(R.id.recruit_release_recruitCount);
		tv_experience = (TextView) findViewById(R.id.recruit_release_experience);
		tv_education = (TextView) findViewById(R.id.recruit_release_education);
		et_describe = (EditText) findViewById(R.id.recruit_release_describe);
		releaseBtn = (Button) findViewById(R.id.recruit_release_button);
		rl_salary.setOnClickListener(this);
		rl_tryout.setOnClickListener(this);
		rl_address.setOnClickListener(this);
		rl_experience.setOnClickListener(this);
		rl_education.setOnClickListener(this);
//		releaseBtn.setOnClickListener(this);
		releaseBtn.setOnClickListener(new NoDoubleClickListener() {
			
			@Override
			public void onNoDoubleClick(View v) {
				applay();
			}
		});
	}
	private void initData(){
		Intent intent = getIntent();
		Bundle bundle = intent.getBundleExtra(GlobalContext.BUNDLE_EDIT);
		if(null != bundle){
			recruitId = bundle.getInt(GlobalContext.BUNDLE_ID, 0);
			et_post.setText(bundle.getString(GlobalContext.BUNDLE_POST));
			tv_salary.setText(bundle.getString(GlobalContext.BUNDLE_SALARY));
			tv_tryout.setText(bundle.getString(GlobalContext.BUNDLE_TRYOUT, ""));
			tv_address.setText(bundle.getString(GlobalContext.BUNDLE_ADDRESS));
			et_recruitCount.setText(bundle.getString(GlobalContext.BUNDLE_COUNT));
			tv_experience.setText(bundle.getString(GlobalContext.BUNDLE_EXPERIENCE));
			tv_education.setText(bundle.getString(GlobalContext.BUNDLE_EDUCATION));
			et_describe.setText(bundle.getString(GlobalContext.BUNDLE_DESCRIBLE));
		}
		/*if(null != recruitId && 0 != recruitId){
			RecruitDetailsManager detailManager = new RecruitDetailsManager(this);
			detailManager.addRecruitDetailsListener(this);
			detailManager.recruitDetails(recruitId, GlobalContext.accountId);
		}*/
	}
	private View showRealase(int layoutId){
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		win.setAttributes(lp);
		win.setWindowAnimations(R.style.buttom_animation);
		View view = LayoutInflater.from(this).inflate(layoutId,null);
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
		return view;
	}
	
	/**
	 * 地区选择器
	 */
	private void initAreaData(){
		//选项选择器
	    pvOptions = new OptionsPickerView(this);
		InputStream input = getResources().openRawResource(R.raw.zone);
		String jsonData = Utils.inputStream2String(input, "utf-8");
		List<Zone> zoneList = (List<Zone>) JsonUtil.toObjectList(jsonData, Zone.class);
		for (Iterator iterator = zoneList.iterator(); iterator.hasNext();) {
			Zone zone = (Zone) iterator.next();
			ChildZone child = new ChildZone();
			child.setId(zone.getId());
			child.setName(zone.getName());
			province_list.add(child);
			provinceList.add(zone.getName());
			LinkedList<ChildZone> linkList = zone.getChildrens();
			city_list.add(linkList);
			ArrayList<String> arrayList = new ArrayList<String>();
			for (int i = 0; i < linkList.size(); i++) {
				arrayList.add(linkList.get(i).getName());
			}
			cityList.add(arrayList);
		}
		
	    pvOptions.setPicker(provinceList, cityList, true);
        pvOptions.setTitle(getResources().getString(R.string.city_selected));
        pvOptions.setCyclic(false);
		
        pvOptions.setSelectOptions(1, 1);
        pvOptions.setOnoptionsSelectListener(new OnOptionsSelectListener() {

			@Override
			public void onOptionsSelect(int options1, int option2, int options3) {
				String areaStr = provinceList.get(options1) + cityList.get(options1).get(option2);
				tv_address.setText(areaStr);
			}
		});
        pvOptions.show();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recruit_release_salary_rl:	// 薪资
			// 隐藏键盘
			Utils.hideSoftInput(RecruitReleaseActivity.this, et_post);
			
			View viewMoney = showRealase(R.layout.job_release_money);
			PickerView pickerMoney = (PickerView) viewMoney.findViewById(R.id.picker_money);
			List<String> datas = new ArrayList<String>();
			String[] xinziStr = getResources().getStringArray(R.array.salary_array);
			for (int i = 0; i < xinziStr.length; i++) {
				datas.add(xinziStr[i]);
			}
			pickerMoney.setData(datas);
			if("".equals(strMoney)){
				strMoney = xinziStr[0];
			}
			pickerMoney.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					strMoney = text;
				}
			});
			Button confirmMoney = (Button) viewMoney.findViewById(R.id.job_money_confirm);
			confirmMoney.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tv_salary.setText(strMoney);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.recruit_release_tryout_rl:// 是否试用
			// 隐藏键盘
			Utils.hideSoftInput(RecruitReleaseActivity.this, et_post);
						
			View viewTryout = showRealase(R.layout.job_release_money);
			PickerView pickerTryout = (PickerView) viewTryout.findViewById(R.id.picker_money);
			List<String> dataTryout = new ArrayList<String>();
			
			for (int i = 0; i < tryoutList.length; i++) {
				dataTryout.add(tryoutList[i]);
			}
			pickerTryout.setData(dataTryout);
			if("".equals(strTryout)){
				strTryout = tryoutList[0];
			}
			pickerTryout.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					// TODO Auto-generated method stub
					strTryout = text;
				}
			});
			Button isTryout = (Button) viewTryout.findViewById(R.id.job_money_confirm);
			isTryout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tv_tryout.setText(strTryout);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.recruit_release_address_rl:	//地区选择
			// 隐藏键盘
			Utils.hideSoftInput(RecruitReleaseActivity.this, et_post);
			initAreaData();
			break;
		case R.id.recruit_release_experience_rl:	// 工作经验
			// 隐藏键盘
			Utils.hideSoftInput(RecruitReleaseActivity.this, et_post);
			View viewYear = showRealase(R.layout.job_release_money);
			PickerView pickerYear = (PickerView) viewYear.findViewById(R.id.picker_money);
			List<String> datasYear = new ArrayList<String>();
			String[] experience = getResources().getStringArray(R.array.recruit_experience_array);
			for (int i = 0; i < experience.length; i++) {
				datasYear.add(experience[i]);
			}
			pickerYear.setData(datasYear);
			if ("".equals(strExperience)) {
				strExperience = experience[0];
			}
			pickerYear.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					// TODO Auto-generated method stub
					strExperience = text;
				}
			});
			Button confirmYear = (Button) viewYear.findViewById(R.id.job_money_confirm);
			confirmYear.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tv_experience.setText(strExperience);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.recruit_release_education_rl:	//学历
			// 隐藏键盘
			Utils.hideSoftInput(RecruitReleaseActivity.this, et_post);
			View viewXueli = showRealase(R.layout.job_release_money);
			PickerView pickerXueli = (PickerView) viewXueli.findViewById(R.id.picker_money);
			List<String> datasXueli = new ArrayList<String>();
			String[] education = getResources().getStringArray(R.array.education_array);
			for (int i = 0; i < education.length; i++) {
				datasXueli.add(education[i]);
			}
			pickerXueli.setData(datasXueli);
			if("".equals(strXueli)){
				strXueli = education[0];
			}
			pickerXueli.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					// TODO Auto-generated method stub
					strXueli = text;
				}
			});
			Button confirmXueli = (Button) viewXueli.findViewById(R.id.job_money_confirm);
			confirmXueli.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tv_education.setText(strXueli);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.right_button://预览
			Intent previewIntent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString(RecruitPreviewActivity.BUNDLE_POST, et_post.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_TRYOUT, tv_tryout.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_SALARY, tv_salary.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_ADDRESS, tv_address.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_RECRUITCOUNT, et_recruitCount.getText().toString().trim() + "人");
			bundle.putString(RecruitPreviewActivity.BUNDLE_EXPERIENCE, tv_experience.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_EDUCATION, tv_education.getText().toString().trim());
			bundle.putString(RecruitPreviewActivity.BUNDLE_DESCRIBLE, et_describe.getText().toString().trim());
			previewIntent.putExtra(RecruitPreviewActivity.BUNDLE_PREVIEW, bundle);
			previewIntent.setClass(this, RecruitPreviewActivity.class);
			startActivity(previewIntent);
			break;
		case R.id.back_button:
			finish();
			break;
//		case R.id.recruit_release_button:// 发布
//			applay();
//			break;
		default:
			break;
		}

	}
	@Override
	public void onRecruitAddFailure(int errorCode, String errorMsg) {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		isClick = false;
	}
	@Override
	public void onRecruitAddSuccess(RecruitListData obj) {
		Notification.toast(this, "发布成功" );
		isClick = false;
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(null == recruitId || 0 == recruitId){
			RecruitListChangeManager.getInstance().notifyAdd(obj);
		}else{
			RecruitAddData addData = new RecruitAddData();
			addData.setId(obj.getId());
			addData.setAccountId(GlobalContext.accountId);
			addData.setSalary(obj.getSalary());
			addData.setTryout(obj.getTryout());
			addData.setPost(obj.getPost());
			addData.setRecruitCount(obj.getRecruitCount() + "");
			addData.setAddress(obj.getAddress());
			addData.setExperience(obj.getExperience());
			addData.setEducation(obj.getEducation());
			addData.setDescribe(obj.getDescribe());
			addData.setStatus(obj.getStatus());
			addData.setDeliverStatus(0);
			RecruitListChangeManager.getInstance().notifyModify(recruitId, addData);
		}
		finish();
	}
	
	private void applay(){
		if(TextUtils.isEmpty(et_post.getText().toString())){
			Notification.toast(this, "选择招聘岗位");
			et_post.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_salary.getText().toString())){
			Notification.toast(this, "选择薪资");
			tv_salary.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_tryout.getText().toString())){
			Notification.toast(this, "选择可否试用");
			tv_tryout.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_address.getText().toString())){
			Notification.toast(this, "选择工作地区");
			tv_address.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_experience.getText().toString())){
			Notification.toast(this, "选择工作经验");
			tv_experience.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_education.getText().toString())){
			Notification.toast(this, "选择学历");
			tv_education.requestFocus();
			return;
		}else if(TextUtils.isEmpty(et_describe.getText().toString())){
			Notification.toast(this, "填写个人描述");
			et_describe.requestFocus();
			return;
		}else if(TextUtils.isEmpty(et_recruitCount.getText().toString())){
			Notification.toast(this, "填写招聘人数");
			et_recruitCount.requestFocus();
			return;
		}
		int recruitCount = Integer.valueOf(et_recruitCount.getText().toString().trim());
		if(0 == recruitCount){
			Notification.toast(this, "招聘人数必须大于0");
			et_recruitCount.requestFocus();
			return;
		}
		
		if(!isClick){
			isClick = true;
			pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
			pDialog.show();
			manager.recruitAdd(recruitId, GlobalContext.accountId, et_post
					.getText().toString().trim(), tv_salary.getText().toString().trim(), 
					tv_tryout.getText().toString().trim(),tv_experience.getText().toString().trim(), 
					Integer.valueOf(et_recruitCount.getText().toString().trim()), 
					tv_education.getText().toString().trim(), et_describe.getText().toString().trim(),
					tv_address.getText().toString().trim());
		}
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
		@Override
		protected void onDestroy() {
			super.onDestroy();
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
		}
}
